<!DOCTYPE html>
<html>
<head>
    <title>产品图片上传</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/bootstrap/icons/bootstrap-icons.css">
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .upload-form {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #333;
            font-size: 16px;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
            font-size: 14px;
        }
        .required::after {
            content: " *";
            color: #d32f2f;
        }
        .submit-btn {
            background-color: #c0a36c;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
            width: 100%;
        }
        .submit-btn:hover {
            background-color: #a88c5a;
        }
        .submit-btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
            font-size: 16px;
        }
        .error {
            color: #d32f2f;
            padding: 12px;
            background-color: #ffebee;
            border-radius: 4px;
            margin: 15px 0;
            font-size: 14px;
        }
        .success {
            color: #2e7d32;
            padding: 12px;
            background-color: #e8f5e8;
            border-radius: 4px;
            margin: 15px 0;
            font-size: 14px;
        }
        .file-input-container {
            position: relative;
            margin-bottom: 15px;
        }
        .file-input {
            width: 100%;
            padding: 10px;
            border: 2px dashed #ccc;
            border-radius: 4px;
            background-color: #f9f9f9;
            text-align: center;
            cursor: pointer;
            transition: border-color 0.3s;
        }
        .file-input:hover {
            border-color: #c0a36c;
        }
        .file-input input[type="file"] {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }
        .file-list {
            margin-top: 15px;
        }
        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            background-color: #f5f5f5;
            border-radius: 4px;
            margin-bottom: 5px;
            font-size: 14px;
        }
        .file-item .file-name {
            flex: 1;
        }
        .file-item .file-size {
            color: #666;
            margin-right: 10px;
        }
        .file-item .remove-btn {
            color: #d32f2f;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 16px;
        }
        .upload-progress {
            margin-top: 15px;
        }
        .progress-bar {
            width: 100%;
            height: 8px;
            background-color: #f0f0f0;
            border-radius: 4px;
            overflow: hidden;
        }
        .progress-fill {
            height: 100%;
            background-color: #c0a36c;
            transition: width 0.3s;
        }
        .progress-text {
            text-align: center;
            margin-top: 5px;
            font-size: 12px;
            color: #666;
        }
        .back-btn {
            display: inline-block;
            padding: 8px 16px;
            background-color: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .back-btn:hover {
            background-color: #5a6268;
        }
        
        /* 搜索结果弹出框样式 */
        .search-results {
            position: absolute;
            background: white;
            border: 1px solid #ccc;
            border-radius: 4px;
            max-height: 200px;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
            display: none;
            width: calc(100% - 2px);
        }
        .search-result-item {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
            font-size: 14px;
        }
        .search-result-item:hover {
            background-color: #f5f5f5;
        }
        .search-result-item:last-child {
            border-bottom: none;
        }
        .product-id-highlight {
            font-weight: bold;
            color: #c0a36c;
        }
        .product-name {
            color: #666;
            margin-left: 8px;
        }
        .product-type {
            font-size: 12px;
            color: #999;
            margin-left: 8px;
        }
        
        /* 产品信息显示区域 */
        .product-info {
            margin-top: 15px;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 4px;
            border-left: 4px solid #c0a36c;
            display: none;
        }
        .product-info h4 {
            margin: 0 0 10px 0;
            color: #333;
        }
        .product-info-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            font-size: 14px;
        }
        .product-info-item {
            margin-bottom: 5px;
        }
        .product-info-label {
            font-weight: bold;
            color: #666;
        }
        .product-info-value {
            color: #333;
        }
    </style>
</head>
<body style="background-color:#fffbf6">
    
    <!-- 状态栏 -->
    {% include 'status_bar.html' %}
    
    <!-- 返回主菜单按钮 -->
    <div style="max-width: 800px; margin: 20px auto 10px auto; padding: 0 20px;">
        <a href="/ej_index" class="btn btn-outline-secondary btn-sm" style="margin-bottom: 10px;">
            <i class="bi bi-arrow-left"></i> 返回主菜单
        </a>
    </div>
    
    <h2 style="max-width: 800px; margin: 0 auto 20px auto; padding: 0 20px;">产品图片上传</h2>

    <div id="loading" class="loading" style="display: none;">正在处理...</div>
    <div id="error" class="error" style="display: none;"></div>
    <div id="success" class="success" style="display: none;"></div>

    <form id="uploadForm" class="upload-form">
        <!-- 产品ID输入 -->
        <div class="form-group" style="position: relative;">
            <label class="required">产品ID</label>
            <input type="text" id="product_id" name="product_id" required 
                   placeholder="请输入产品ID，如：EJ-JD-240831123456">
            <!-- 搜索结果弹出框 -->
            <div id="searchResults" class="search-results"></div>
        </div>
        
        <!-- 产品信息显示区域 -->
        <div id="productInfo" class="product-info">
            <h4>产品信息</h4>
            <div class="product-info-details" id="productInfoDetails">
                <!-- 产品信息将在这里动态显示 -->
            </div>
        </div>

        <!-- 图片上传区域 -->
        <div class="form-group">
            <label class="required">选择图片</label>
            <div class="file-input-container">
                <div class="file-input">
                    <span>点击或拖拽图片到这里</span>
                    <input type="file" id="product_images" name="product_images" 
                           accept=".jpg,.jpeg,.png" multiple required>
                </div>
            </div>
            <div class="file-list" id="fileList"></div>
        </div>

        <!-- 上传进度 -->
        <div class="upload-progress" id="progressContainer" style="display: none;">
            <div class="progress-bar">
                <div class="progress-fill" id="progressFill" style="width: 0%"></div>
            </div>
            <div class="progress-text" id="progressText">0%</div>
        </div>

        <button type="submit" class="submit-btn" id="submitBtn">开始上传</button>
    </form>

    <script src="/static/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        // 文件列表管理
        const fileList = document.getElementById('fileList');
        const fileInput = document.getElementById('product_images');
        const progressContainer = document.getElementById('progressContainer');
        const progressFill = document.getElementById('progressFill');
        const progressText = document.getElementById('progressText');
        const submitBtn = document.getElementById('submitBtn');
        const loading = document.getElementById('loading');
        const error = document.getElementById('error');
        const success = document.getElementById('success');

        let selectedFiles = [];

        // 文件选择处理
        fileInput.addEventListener('change', function(e) {
            const files = Array.from(e.target.files);
            selectedFiles = files;
            updateFileList();
            
            // 更新文件输入以确保FormData能正确获取文件
            const dataTransfer = new DataTransfer();
            selectedFiles.forEach(file => dataTransfer.items.add(file));
            fileInput.files = dataTransfer.files;
        });

        // 拖拽功能
        const fileInputContainer = document.querySelector('.file-input');
        fileInputContainer.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.borderColor = '#c0a36c';
            this.style.backgroundColor = '#f0f0f0';
        });

        fileInputContainer.addEventListener('dragleave', function(e) {
            e.preventDefault();
            this.style.borderColor = '#ccc';
            this.style.backgroundColor = '#f9f9f9';
        });

        fileInputContainer.addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.borderColor = '#ccc';
            this.style.backgroundColor = '#f9f9f9';
            
            const files = Array.from(e.dataTransfer.files).filter(file => 
                file.type.startsWith('image/') && 
                (file.name.toLowerCase().endsWith('.jpg') || 
                 file.name.toLowerCase().endsWith('.jpeg') || 
                 file.name.toLowerCase().endsWith('.png'))
            );
            
            selectedFiles = files;
            updateFileList();
            
            // 更新文件输入以确保FormData能正确获取文件
            const dataTransfer = new DataTransfer();
            selectedFiles.forEach(file => dataTransfer.items.add(file));
            fileInput.files = dataTransfer.files;
        });

        // 更新文件列表显示
        function updateFileList() {
            fileList.innerHTML = '';
            
            if (selectedFiles.length === 0) {
                const emptyMsg = document.createElement('div');
                emptyMsg.textContent = '未选择任何图片';
                emptyMsg.style.color = '#666';
                emptyMsg.style.textAlign = 'center';
                emptyMsg.style.padding = '10px';
                fileList.appendChild(emptyMsg);
                return;
            }

            selectedFiles.forEach((file, index) => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                
                const fileName = document.createElement('span');
                fileName.className = 'file-name';
                fileName.textContent = file.name;
                
                const fileSize = document.createElement('span');
                fileSize.className = 'file-size';
                fileSize.textContent = formatFileSize(file.size);
                
                const removeBtn = document.createElement('button');
                removeBtn.className = 'remove-btn';
                removeBtn.textContent = '×';
                removeBtn.onclick = () => removeFile(index);
                
                fileItem.appendChild(fileName);
                fileItem.appendChild(fileSize);
                fileItem.appendChild(removeBtn);
                fileList.appendChild(fileItem);
            });
        }

        // 移除文件
        function removeFile(index) {
            selectedFiles.splice(index, 1);
            updateFileList();
            
            // 更新文件输入
            const dataTransfer = new DataTransfer();
            selectedFiles.forEach(file => dataTransfer.items.add(file));
            fileInput.files = dataTransfer.files;
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 表单提交处理
        document.getElementById('uploadForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const productId = document.getElementById('product_id').value.trim();
            
            if (!productId) {
                showError('请输入产品ID');
                return;
            }
            
            if (selectedFiles.length === 0) {
                showError('请选择至少一张图片');
                return;
            }

            // 验证文件类型和大小
            for (const file of selectedFiles) {
                if (!file.type.startsWith('image/')) {
                    showError('请选择图片文件（jpg、jpeg、png格式）');
                    return;
                }
                
                if (file.size > 10 * 1024 * 1024) { // 10MB限制
                    showError(`文件 ${file.name} 大小超过10MB限制`);
                    return;
                }
            }

            uploadFiles(productId);
        });

        // 显示错误信息
        function showError(message) {
            error.style.display = 'block';
            error.textContent = message;
            success.style.display = 'none';
            
            // 3秒后自动隐藏错误信息
            setTimeout(() => {
                error.style.display = 'none';
            }, 3000);
        }

        // 显示成功信息
        function showSuccess(message) {
            success.style.display = 'block';
            success.textContent = message;
            error.style.display = 'none';
        }

        // 更新进度条
        function updateProgress(percentage) {
            progressFill.style.width = percentage + '%';
            progressText.textContent = percentage + '%';
        }

        // 上传文件
        function uploadFiles(productId) {
            const formData = new FormData();
            formData.append('product_id', productId);
            
            // 添加所有文件
            selectedFiles.forEach(file => {
                formData.append('product_images', file);
            });

            // 显示进度条
            progressContainer.style.display = 'block';
            loading.style.display = 'block';
            submitBtn.disabled = true;
            submitBtn.textContent = '上传中...';
            error.style.display = 'none';
            success.style.display = 'none';

            // 初始化进度
            updateProgress(0);

            fetch('/upload_product_image', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('上传失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.res === 'ok') {
                    showSuccess(`成功上传 ${data.processed_files.length} 张图片`);
                    updateProgress(100);
                    
                    // 重置表单
                    document.getElementById('uploadForm').reset();
                    selectedFiles = [];
                    updateFileList();
                    
                    // 显示处理后的文件列表
                    if (data.processed_files && data.processed_files.length > 0) {
                        const fileList = data.processed_files.join(', ');
                        success.textContent += `\n处理文件: ${fileList}`;
                    }
                } else {
                    throw new Error(data.message || '上传失败');
                }
            })
            .catch(error => {
                showError('上传失败: ' + error.message);
                updateProgress(0);
            })
            .finally(() => {
                loading.style.display = 'none';
                submitBtn.disabled = false;
                submitBtn.textContent = '开始上传';
                
                // 3秒后隐藏进度条
                setTimeout(() => {
                    progressContainer.style.display = 'none';
                }, 3000);
            });

            // 模拟进度更新（实际进度需要后端支持）
            let progress = 0;
            const progressInterval = setInterval(() => {
                progress += 5;
                if (progress <= 95) {
                    updateProgress(progress);
                } else {
                    clearInterval(progressInterval);
                }
            }, 200);
        }

        // 产品ID搜索相关变量
        const productIdInput = document.getElementById('product_id');
        const searchResults = document.getElementById('searchResults');
        const productInfo = document.getElementById('productInfo');
        const productInfoDetails = document.getElementById('productInfoDetails');
        let searchTimeout = null;
        let activeSearchRequest = null; // 用于中止之前的请求

        // 产品ID输入事件监听
        productIdInput.addEventListener('input', function(e) {
            const keyword = e.target.value.trim();
            
            // 清除之前的定时器
            clearTimeout(searchTimeout);
            
            // 中止之前的请求（如果存在）
            if (activeSearchRequest) {
                activeSearchRequest.abort();
                activeSearchRequest = null;
            }
            
            // 如果输入为空，隐藏搜索结果
            if (!keyword) {
                searchResults.style.display = 'none';
                productInfo.style.display = 'none';
                return;
            }
            
            // 设置防抖，300ms后执行搜索
            searchTimeout = setTimeout(() => {
                searchProductIds(keyword);
            }, 300);
        });

        // 点击页面其他区域隐藏搜索结果
        document.addEventListener('click', function(e) {
            if (!productIdInput.contains(e.target) && !searchResults.contains(e.target)) {
                searchResults.style.display = 'none';
            }
        });

        // 键盘导航支持
        productIdInput.addEventListener('keydown', function(e) {
            const visibleItems = searchResults.querySelectorAll('.search-result-item');
            
            if (visibleItems.length === 0) return;

            const activeItem = searchResults.querySelector('.search-result-item.active');
            let nextIndex = -1;

            if (e.key === 'ArrowDown') {
                e.preventDefault();
                if (!activeItem) {
                    nextIndex = 0;
                } else {
                    nextIndex = Array.from(visibleItems).indexOf(activeItem) + 1;
                    if (nextIndex >= visibleItems.length) nextIndex = 0;
                }
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                if (!activeItem) {
                    nextIndex = visibleItems.length - 1;
                } else {
                    nextIndex = Array.from(visibleItems).indexOf(activeItem) - 1;
                    if (nextIndex < 0) nextIndex = visibleItems.length - 1;
                }
            } else if (e.key === 'Enter' && activeItem) {
                e.preventDefault();
                activeItem.click();
                return;
            } else if (e.key === 'Escape') {
                searchResults.style.display = 'none';
                return;
            }

            if (nextIndex >= 0) {
                // 移除所有active类
                visibleItems.forEach(item => item.classList.remove('active'));
                // 添加active类到当前项
                visibleItems[nextIndex].classList.add('active');
            }
        });

        // 搜索产品ID
        function searchProductIds(keyword) {
            if (keyword.length < 1) {
                searchResults.style.display = 'none';
                return;
            }

            // 创建AbortController用于中止请求
            const controller = new AbortController();
            activeSearchRequest = controller;

            fetch(`/search_product_ids?keyword=${encodeURIComponent(keyword)}`, {
                signal: controller.signal
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('搜索失败');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success && data.data && data.data.length > 0) {
                        displaySearchResults(data.data, keyword);
                    } else {
                        searchResults.style.display = 'none';
                    }
                    activeSearchRequest = null;
                })
                .catch(error => {
                    if (error.name === 'AbortError') {
                        console.log('搜索请求被中止');
                    } else {
                        console.error('搜索产品ID失败:', error);
                        searchResults.style.display = 'none';
                    }
                    activeSearchRequest = null;
                });
        }

        // 显示搜索结果
        function displaySearchResults(results, keyword) {
            searchResults.innerHTML = '';
            
            results.forEach(product => {
                const item = document.createElement('div');
                item.className = 'search-result-item';
                
                // 高亮匹配的关键词
                const highlightedId = product.product_id.replace(
                    new RegExp(keyword, 'gi'),
                    match => `<span class="product-id-highlight">${match}</span>`
                );
                
                item.innerHTML = `
                    <div>
                        <span class="product-id-highlight">${highlightedId}</span>
                        <span class="product-name">${product.product_name || '未命名'}</span>
                        <span class="product-type">${product.type || product.product_type === 'culture' ? '文创' : '饰品'}</span>
                    </div>
                `;
                
                item.addEventListener('click', () => {
                    selectProduct(product.product_id);
                });
                
                searchResults.appendChild(item);
            });
            
            searchResults.style.display = 'block';
        }

        // 选择产品
        function selectProduct(productId) {
            productIdInput.value = productId;
            searchResults.style.display = 'none';
            
            // 获取产品详细信息
            getProductDetails(productId);
        }

        // 获取产品详细信息
        function getProductDetails(productId) {
            fetch(`/get_product_details?product_id=${encodeURIComponent(productId)}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取产品信息失败');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        displayProductInfo(data.data);
                    } else {
                        productInfo.style.display = 'none';
                    }
                })
                .catch(error => {
                    console.error('获取产品详情失败:', error);
                    productInfo.style.display = 'none';
                });
        }

        // 显示产品信息
        function displayProductInfo(productData) {
            productInfoDetails.innerHTML = '';
            
            // 添加封面图片显示
            if (productData.cover_image_url) {
                const imageContainer = document.createElement('div');
                imageContainer.className = 'product-info-item';
                imageContainer.style.gridColumn = '1 / -1'; // 跨所有列
                imageContainer.style.textAlign = 'center';
                imageContainer.innerHTML = `
                    <div style="margin-bottom: 10px;">
                        <img src="${productData.cover_image_url}" 
                             alt="产品封面图" 
                             style="max-width: 200px; max-height: 200px; 
                                    border: 1px solid #ddd; border-radius: 4px;
                                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    </div>
                `;
                productInfoDetails.appendChild(imageContainer);
            }
            
            const infoItems = [
                { label: '产品ID', value: productData.product_id },
                { label: '产品名称', value: productData.product_name },
                { label: '产品类型', value: productData.type_1 || productData.type },
                { label: '子类型', value: productData.type_2 },
                { label: '五行属性', value: productData.wu_xings },
                { label: '颜色', value: productData.colors },
                { label: '主要材质', value: productData.major_material || productData.materials },
                { label: '设计师', value: productData.designer_name },
                { label: '设计日期', value: formatDate(productData.designed_date) },
                { label: '产品类别', value: productData.product_type === 'culture' ? '文创产品' : '饰品产品' }
            ];
            
            infoItems.forEach(item => {
                if (item.value) {
                    const infoItem = document.createElement('div');
                    infoItem.className = 'product-info-item';
                    infoItem.innerHTML = `
                        <span class="product-info-label">${item.label}：</span>
                        <span class="product-info-value">${item.value}</span>
                    `;
                    productInfoDetails.appendChild(infoItem);
                }
            });
            
            productInfo.style.display = 'block';
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN');
            } catch (e) {
                return dateString;
            }
        }

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            updateFileList();
        });
    </script>
</body>
</html>
